<?php

/**
 * Created by PhpStorm.
 * User: DaXiong
 * Date: 2021/4/8
 * Time: 12:02 AM
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;

use App\Models\Consultation;
use App\Models\ConsultationRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ConsultationController extends Controller
{

    /**
     * 创建 问诊
     * @param Request $request
     * @return $this
     */
    public function create(Request $request)
    {
        $validate = $request->validate([
            'describe' => 'required',
            'images'   => [
                'nullable',
                'array'
            ],
        ]);

        $validate['images'] = implode(',', $validate['images']);
        $validate['images'] = str_replace(trim(config('app.url'), '/'), '', $validate['images']);
        $validate['user_id'] = auth('api')->id();
        $validate['status'] = 1;
        $validate['created_at'] = now();
        if (Consultation::query()->create(Consultation::fillableFromArray($validate))) {
            return $this->success([]);
        };
        return $this->error();
    }


    /**
     * 上传 问诊图片
     * @param Request $request
     * @return $this
     */
    public function upload(Request $request)
    {
        $file = $request->file('image');
        //验证是否上传成功
        if ($file->isValid()) {
            //   $originalName = $file->getClientOriginalName();// 原文件名
            $ext = $file->getClientOriginalExtension();// 扩展名
            //   $type = $file->getClientMimeType();
            $realPath = $file->getRealPath();// 临时绝对路径
            $fileName = date('Ymd') . '/' . uniqid() . '.' . $ext;// 自定义文件名
            //存储
            $bool = Storage::disk('image')->put($fileName, file_get_contents($realPath));
            return $this->success(['uri_path' => '/uploads/' . $fileName]);
        }
        return $this->error();
    }


    /**
     * 获取 问诊列表
     * @return $this
     */
    public function index()
    {
        $uid = auth('api')->id();
        $field = [
            '*'
        ];
        $list = Consultation::query()->where('user_id', $uid)->orderBy('id', 'desc')->paginate($this->limit, $field, 'page', $this->page);
        foreach ($list->items() as $item) {
            $cover = '';
            if ($item->images) {
                $cover = trim(config('app.url'), '/') . explode(',', $item->images)[0];
            }
            $item->cover = $cover;
            $item->created_at = substr($item->created_at, 0, 10);
        }
        return $this->success($list->toArray());
    }

    // 详情
    public function detail(Request $request)
    {
        $id = $request->get('id');
        $user_id = auth('api')->id();

        $data = Consultation::whereUserId($user_id)
            ->where('id', $id)
            ->first();
        if (empty($data)) {
            return $this->error(500, '数据不存在');
        } else {
            $app_url = config('app.url');
            $images = [];
            foreach (explode(',', $data->images) as $url) {
                $images[] = trim($app_url, '.') . $url;
            }
            $data->images = $images;
            return $this->writeJson(0, $data);
        }
    }

    /**
     * 获取 咨询记录
     * @param Request $request
     * @return $this
     */
    public function record(Request $request)
    {
        $validate = $request->validate([
            'consultation_id' => 'required',
        ], [], [
            'consultation_id' => '问诊ID',
        ]);
        $field = [
            '*'
        ];
        $list = ConsultationRecord::query()->where('consultation_id', $validate['consultation_id'])->orderBy('id', 'asc')->limit(50)->get();
        return $this->success($list->toArray());
    }

    /**
     * 创建 提问
     * @param Request $request
     * @return $this
     */
    public function recordAsk(Request $request)
    {

        $validate = $request->validate([
            'consultation_id' => 'required',
            'content'         => 'required',
        ]);
        $validate['asker_id'] = auth('api')->id();
        $validate['created_at'] = now();
        if (ConsultationRecord::query()->create(ConsultationRecord::fillableFromArray($validate))) {
            Consultation::whereId($request->post('consultation_id'))
                ->update([
                    'status' => 1
                ]);
            return $this->success([]);
        };
        return $this->error();
    }
}
